package com.linjiahao.userCenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linjiahao.servicebase.common.BaseConstant;
import com.linjiahao.servicebase.common.RedisService;
import com.linjiahao.servicebase.common.ResultMap;
import com.linjiahao.servicebase.exception.ErrorMessage;
import com.linjiahao.servicebase.exception.WebChatException;
import com.linjiahao.servicebase.util.JWTUtil;
import com.linjiahao.userCenter.domain.ChatFriend;
import com.linjiahao.userCenter.domain.ChatUserInfo;
import com.linjiahao.userCenter.mapper.ChatFriendMapper;
import com.linjiahao.userCenter.mapper.ChatUserInfoMapper;
import com.linjiahao.userCenter.service.ChatUserInfoService;
import com.linjiahao.userCenter.vo.PersonInfoVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName ChatUserInfoServiceImpl
 * @Description: 用户服务抽象实现类
 * @Author linjiahao
 * @Date 29/12/2021
 **/
@Service
public class ChatUserInfoServiceImpl extends ServiceImpl<ChatUserInfoMapper, ChatUserInfo> implements ChatUserInfoService{

    @Resource
    private RedisService redisService;

    @Resource
    private ChatUserInfoMapper chatUserInfoMapper;

    @Resource
    private ChatFriendMapper chatFriendMapper;

    @Override
    public ResultMap userLogin(String phone, String code,HttpServletResponse response) {
        //校验验证码
        String authCode = redisService.getString(String.format(BaseConstant.MSM_PHONE_CODE_KEY, phone));
        if(StringUtils.isNotBlank(authCode)){
            if(!authCode.equals(code)){
                throw new WebChatException(ErrorMessage.VERIFICATION_CODE_ERROR.getErrorCode(),ErrorMessage.VERIFICATION_CODE_ERROR.getMessage());
            }
        }else {
            throw new WebChatException(ErrorMessage.VERIFICATION_CODE_HAS_EXPIRED.getErrorCode(),ErrorMessage.VERIFICATION_CODE_HAS_EXPIRED.getMessage());
        }
        ChatUserInfo chatUserInfo = this.baseMapper.selectOne(new QueryWrapper<ChatUserInfo>().lambda().eq(ChatUserInfo::getPhone, phone));
        String token = "";
        if(chatUserInfo == null){
            //用户新增
            ChatUserInfo info = new ChatUserInfo().getInitUserInfo(phone);
            this.baseMapper.insert(info);
            //生成token
            token = JWTUtil.generateTokenWithUserId(info.getUserId());
            redisService.set(String.format(BaseConstant.USER_LOGIN_SUCCESS,token),info,7200);
            chatUserInfo = info;
        }else {
            token = JWTUtil.generateTokenWithUserId(chatUserInfo.getUserId());
            redisService.set(String.format(BaseConstant.USER_LOGIN_SUCCESS,token),chatUserInfo,7200);
        }
        response.setHeader("Access-Control-Expose-Headers",BaseConstant.HEADER_TOKEN_KEY);
        response.setHeader(BaseConstant.HEADER_TOKEN_KEY,token);
        return ResultMap.ok().data("userInfo",chatUserInfo);
    }

    @Override
    public void logout(String authToken) {
        redisService.del(String.format(BaseConstant.USER_LOGIN_SUCCESS,authToken));
    }

    @Override
    public ResultMap getUserInfoBytoken(String authToken) {
        ChatUserInfo chatUserInfo = redisService.get(String.format(BaseConstant.USER_LOGIN_SUCCESS,authToken), ChatUserInfo.class);
        if(chatUserInfo ==null){
            throw new WebChatException(ErrorMessage.TOKEN_IS_NOT_VALIDATE.getErrorCode(),ErrorMessage.TOKEN_IS_NOT_VALIDATE.getMessage());
        }
        return ResultMap.ok().data("userInfo",chatUserInfo);
    }

    @Override
    public List<PersonInfoVO> searchPerson(String keyWord,Long userId) {
        List<PersonInfoVO> list = chatUserInfoMapper.searchPerson(keyWord);
        //排掉已加好友的
        QueryWrapper<ChatFriend> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ChatFriend::getUserId,userId).eq(ChatFriend::getIsPass,BaseConstant.Pass)
                .eq(ChatFriend::getIsDelete,BaseConstant.Not_Pass).select(ChatFriend::getFriendId);
        List<ChatFriend> friendList = chatFriendMapper.selectList(queryWrapper);
        List<Long> friendIds = friendList.stream().map(ChatFriend::getFriendId).collect(Collectors.toList());
        list = list.stream().filter(m ->{
            if(m.getUserId().equals(userId) || friendIds.contains(m.getUserId())){
                return false;
            }
            return true;
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<ChatUserInfo> getUserInfoList(List<Long> userIds) {
        QueryWrapper<ChatUserInfo> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(ChatUserInfo::getUserId,userIds).eq(ChatUserInfo::getIsDelete,BaseConstant.Not_Pass)
                .select(ChatUserInfo::getImg,ChatUserInfo::getNickName,ChatUserInfo::getUserId);
        List<ChatUserInfo> list = this.baseMapper.selectList(wrapper);
        return list;
    }
}
